<?php

namespace App\Http\Controllers\Mini\Circle;

use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\HouseLease;
use App\Models\HouseOption;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class HouseController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();

        $this->user_id = $id;
    }

    public function getHouseOption()
    {
        $data = HouseOption::query()->select('id', 'name', 'values', 'type', 'required')->where('state', 1)->get()->each(function ($item) {
            /**
             * 给前端返回数组，方便遍历
             */
            $item['values'] = json_decode($item['values'], true);
            return $item;
        });

        return $this->success($data);
    }

    public function getOption()
    {
        $data = [
            'type' => ['name' => '出租类型', 'values' => ['整租', '合租']],
            'pay_method' => ['name' => '付款方式', 'values' => ['押一付一', '押一付三', '任何方式']],
            'house_type' => ['name' => '户型', 'values' => ['一室一厅', '二室一厅一卫', '三室一厅一卫', '四室一厅一卫', '五室一厅一卫']],
            'direction' => ['name' => '朝向', 'values' => ['东', '西', '南', '北']],
            'renovation' => ['name' => '装修', 'values' => ['精装修', '普通装修', '毛坯房']],
            'house_type1' => ['name' => '房屋类型', 'values' => ['普通住宅', '高档小区', '别墅']]
        ];

        return $this->success($data);
    }

    public function index(Request $request)
    {
        $type = $request->get('type');
        $house_type = $request->get('house_type');
        $where = [];

        //添加可选参数
        if ($house_type) {
            $where[] = ['type', '=', $house_type];
        }
        //只获取我发布的房源信息
        if ($type == 'my') {
            //需要先登录
            $user_id = $this->user_id;
            if (!$user_id) {
                return $this->error('请先登录');
            }
            $where[] = ['user_id', '=', $user_id];
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;


        //发布时间倒序
        $data = HouseLease::query()->with('community:community_id,community_name')->select('id', 'title', 'money', 'image', 'more_option', 'describe', 'type', 'community_id', 'area', 'direction', 'created_at')->where($where)->orderByDesc('created_at')->offset($offset)->limit($limit)->get()->each(function ($item) {
            $item['more_option'] = json_decode($item['more_option'], true);
            return $item;
        });
        $response['data'] = $data;
        $response['count'] = HouseLease::query()->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);
        return $this->success($response, '请求成功');
    }

    //发布出租信息
    public function store(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $data = $request->post();

        $res = $this->checkData($data);
        if ($res['code'] == 200) {
            $data['user_id'] = $user_id;
            HouseLease::query()->create($data);

            return $this->success();
        }
        return $this->error($res['msg'], $res['data']);
    }


    public function update(Request $request, $id)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            $this->error('请先登录');
        }

        $data = $request->post();

        $res = $this->checkData($data);

        if ($res['code'] == 200) {
            $data['user_id'] = $user_id;
            $result = HouseLease::query()->where('id', $id)->update($data);
            return $result ? $this->success() : $this->error();
        }

        return $this->error($res['msg']);
    }

    public function show($id)
    {
        //try捕获异常，查询使用firstOrFail方法，如果查询的内容不存在，会触发HTTP404的异常。
        try {
            $data = HouseLease::query()->with('community:community_id,community_address,city,community_name')->where('id', $id)->firstOrFail()->toArray();

            if (isset($data['community']['city'])) {
                //查询城市名
                $data['city'] = Area::query()->where('id', $data['community']['city'])->value('name');
            }
            $data['more_option'] = json_decode($data['more_option'], true);

            $address = $data['community']['community_address'] ?? null;
            if ($address) {
                $address .= $data['community']['community_name'];
                $res = $this->getLocation($address);
                $data['location'] = ($res['code'] == 200) ? $res['data']['location'] : null;
                //请求高德地图api，获取经纬度
            }

            //TODO：返回给前端图片名
            if (!empty($data['more_option']['房屋配置'])) {
                $contrast = ['床' => 'one', '衣柜' => 'two', '床头柜' => 'sixteen', '空调' => 'four', '热水器' => 'eight', '智能门锁' => 'eighteen', '洗浴' => 'eleven', '沙发' => 'fifteen', '微波炉' => 'nine', '卫生间' => 'nineteen', '电视' => 'seven', '电磁炉' => 'ten', '冰箱' => 'thirteen', '桌椅' => 'three', '洗衣机' => 'twelve', 'wifi' => 'wifi', '暖气' => 'six', '厨房' => 'seventeen'];
                $arr = [];
                foreach ($data['more_option']['房屋配置'] as $v) {
                    $icon = $contrast[$v] ?? false;
                    $arr[$v] = $icon ? asset('images/option/' . $icon . '.png') : $icon;
                }
                $data['more_option']['房屋配置'] = $arr;
            }

            $data['updated_at'] = $this->getTime($data['updated_at'], true);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }


        return $this->success($data);
    }

    public function destroy($id)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $res = HouseLease::query()->where('id', $id)->delete();
        return $res ? $this->success([], '删除成功') : $this->error();
    }

    //检查数据是否合法
    private function checkData($data)
    {
        $validator = Validator::make($data, [
            'title' => 'required|max:255',
            'money' => 'required',
            'image' => 'required',
            'images' => 'required',
            'more_option' => 'required|json',
            'describe' => 'required',
            'renovation' => 'required',
            'type' => 'required|in:1,2',
            'pay_method' => 'required',
            'community_id' => 'required|numeric',
            'area' => 'required|numeric',
            'house_type1' => 'required',
            'username' => 'required',
            'storey' => 'required',
            'direction' => ['required', Rule::in(['东', '西', '南', '北'])],
            'call' => 'required',
            'phone' => 'required|regex:/^1[3456789][0-9]{9}$/'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors->first());
        }

        $more_option = json_decode($data['more_option'], true);

        $option = HouseOption::query()->select('name', 'values', 'type', 'required')->where('state', 1)->get()->toArray();
        //查询更多信息里的必选参数
        $requestOption = array_filter($option, function ($item) {
            return $item['required'] === 1;
        });
        //获取必填项所有的name
        $requestOptionName = array_column($requestOption, 'name');
        //前端提交更多信息所有的key
        $key = array_keys($more_option);
        $check = array_diff($requestOptionName, $key);

        if (!empty($check)) {
            return $this->error('more_option中以下参数未提交:', array_values($check));
        }

        //是否存在空值
        foreach ($more_option as $key => $value) {
            if (empty($value)) {
                return $this->error($key . '：的值为空');
            }
        }

        return $this->success();
    }


    //出租房屋图片上传
    public function uploadImg(Request $request)
    {
        if ($this->user_id) {
            return $this->error('请先登录');
        }

        if ($request->hasFile('file')) {
            //获取图片
            $file = $request->file('file');
            //验证图片合法性
            $res = $this->checkFile($file, ['png', 'jpg', 'jpeg']);
            if ($res === true) {
                $path = $file->store('images/mini/circle/house_lease');
                if ($path) {
                    return $this->success(['path' => $path], '上传成功');
                }

            }
            return $this->error($res);
        }

        return $this->error('没有上传图片');
    }

    /**
     * 验证文件合法性
     * @param \Illuminate\Http\UploadedFile $file
     * @param array $extension
     * @param int $size 2m
     * @return bool|string
     */
    private function checkFile($file, $extension, $size = 2048000)
    {
        $fileExtension = strtolower($file->extension());
        if (!in_array($fileExtension, $extension)) {
            return '文件类型不允许';
        }

        $fileSize = $file->getSize();
        if ($fileSize >= $size) {
            return '图片大于2M';
        }

        return true;
    }

    /**
     * 判断几天前
     */
    private function getTime($targetTime, $time = 'Y-m-d')
    {

        $targetTime = strtotime($targetTime);

        // 今天最大时间
        $todayLast = strtotime(date('Y-m-d 23:59:59'));
        $agoTimeTrue = time() - $targetTime;
        $agoTime = $todayLast - $targetTime;
        $agoDay = floor($agoTime / 86400);

        if ($agoTimeTrue < 60) {
            $result = '刚刚';
        } elseif ($agoTimeTrue < 3600) {
            $result = (ceil($agoTimeTrue / 60)) . '分钟前';
        } elseif ($agoTimeTrue < 3600 * 12) {
            $result = $result = (ceil($agoTimeTrue / 3600)) . '小时前';
        } elseif ($agoDay >= 0 && $agoDay < 16) {
            $result = $result = $agoDay . '天前';
        } else {
            $format = date('Y') != date('Y', $targetTime) ? "Y-m-d H:i:s" : "$time";
            $result = date($format, $targetTime);
        }
        return $result;
    }

    /**
     * 高德API获取经纬度
     */
    private function getLocation($address)
    {
        $config = config('amap');

        $api = $config['api'];
        $key = $config['key'];

        $url = $api . '?address=' . $address . '&output=json&key=' . $key;
        $data = json_decode(file_get_contents($url), true);
        if ($data['status'] == 1) {
            return ['code' => 200, 'msg' => 'success', 'data' => ['location' => $data['geocodes'][0]['location']]];
        } else {
            return ['code' => 400, 'msg' => $data['info']];
        }
    }
}
